<template>
  <div class="dept-heat-container">
    <h2>部门领用热度</h2>
    
    <el-card class="filter-card">
      <div class="filter-controls">
        <el-select v-model="timeRange" size="small" @change="loadHeatData">
          <el-option label="近30天" value="30"></el-option>
          <el-option label="近90天" value="90"></el-option>
          <el-option label="近180天" value="180"></el-option>
          <el-option label="近一年" value="365"></el-option>
        </el-select>
        <el-select v-model="assetType" size="small" @change="loadHeatData">
          <el-option label="全部资产" value="all"></el-option>
          <el-option label="电子设备" value="电子设备"></el-option>
          <el-option label="办公设备" value="办公设备"></el-option>
          <el-option label="办公家具" value="办公家具"></el-option>
          <el-option label="无形资产" value="无形资产"></el-option>
        </el-select>
        <el-button type="primary" size="small" @click="exportHeatMap">导出热力图</el-button>
      </div>
    </el-card>
    
    <el-row :gutter="20">
      <el-col :span="24" :lg="16">
        <el-card class="heatmap-card">
          <template #header>
            <div class="card-header">
              <span>部门领用热度地图</span>
            </div>
          </template>
          <div ref="heatmapContainer" class="heatmap-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="24" :lg="8">
        <el-card class="ranking-card">
          <template #header>
            <div class="card-header">
              <span>部门领用排行榜</span>
            </div>
          </template>
          <div class="ranking-list">
            <div 
              v-for="(item, index) in rankingData" 
              :key="item.deptName"
              class="ranking-item"
              :class="{ 'top-three': index < 3 }"
            >
              <div class="ranking-number">{{ index + 1 }}</div>
              <div class="ranking-info">
                <div class="dept-name">{{ item.deptName }}</div>
                <div class="usage-count">领用次数: {{ item.usageCount }}</div>
              </div>
              <div class="ranking-value">
                <el-progress 
                  :percentage="item.percentage" 
                  :color="getProgressColor(index)"
                  :show-text="false"
                ></el-progress>
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="summary-card">
          <template #header>
            <div class="card-header">
              <span>统计摘要</span>
            </div>
          </template>
          <div class="summary-grid">
            <div class="summary-item">
              <div class="summary-value">{{ totalUsage }}</div>
              <div class="summary-label">总领用次数</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ mostActiveDept }}</div>
              <div class="summary-label">最活跃部门</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ avgUsagePerDept }}</div>
              <div class="summary-label">平均领用次数</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ mostPopularCategory }}</div>
              <div class="summary-label">最受欢迎类别</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'DeptHeat',
  setup() {
    const heatmapContainer = ref(null)
    const chartInstance = ref(null)
    const timeRange = ref('90')
    const assetType = ref('all')
    const heatData = ref([])
    const rankingData = ref([])
    
    // 计算属性
    const totalUsage = computed(() => {
      return rankingData.value.reduce((sum, item) => sum + item.usageCount, 0)
    })
    
    const mostActiveDept = computed(() => {
      return rankingData.value.length > 0 ? rankingData.value[0].deptName : '-'  
    })
    
    const avgUsagePerDept = computed(() => {
      if (rankingData.value.length === 0) return 0
      return Math.round(totalUsage.value / rankingData.value.length)
    })
    
    const mostPopularCategory = computed(() => {
      // 简化实现，实际项目中可以从后端获取
      const categoryMap = {
        '技术部': '电子设备',
        '市场部': '办公设备',
        '财务部': '办公家具',
        '人力资源部': '电子设备',
        '行政部': '办公设备'
      }
      return categoryMap[mostActiveDept.value] || '-'  
    })
    
    // 加载热度数据
    const loadHeatData = async () => {
      try {
        const params = {
          timeRange: parseInt(timeRange.value),
          assetType: assetType.value
        }
        
        const response = await axios.get('/api/statistics/dept-heat', {
          params
        })
        
        if (response.code === 200 && response.data) {
          heatData.value = response.data.heatData || []
          rankingData.value = response.data.rankingData || []
          initHeatmap()
        } else {
          // 使用模拟数据
          setMockData()
        }
      } catch (error) {
        console.error('获取部门领用热度数据失败:', error)
        setMockData()
      }
    }
    
    // 设置模拟数据
    const setMockData = () => {
      // 模拟热力图数据 (部门 vs 月份)
      const months = ['7月', '8月', '9月', '10月', '11月']
      const depts = ['技术部', '市场部', '财务部', '人力资源部', '行政部']
      
      const mockHeatData = []
      depts.forEach((dept, deptIndex) => {
        months.forEach((month, monthIndex) => {
          // 生成随机热度值，技术部和市场部热度更高
          let value = Math.floor(Math.random() * 20)
          if (deptIndex < 2) {
            value += 10 + Math.floor(Math.random() * 30)
          }
          mockHeatData.push([monthIndex, deptIndex, value])
        })
      })
      
      heatData.value = mockHeatData
      
      // 生成排行数据
      rankingData.value = [
        { deptName: '技术部', usageCount: 156, percentage: 100 },
        { deptName: '市场部', usageCount: 128, percentage: 82 },
        { deptName: '财务部', usageCount: 89, percentage: 57 },
        { deptName: '人力资源部', usageCount: 75, percentage: 48 },
        { deptName: '行政部', usageCount: 62, percentage: 40 }
      ]
      
      initHeatmap()
    }
    
    // 初始化热力图
    const initHeatmap = () => {
      nextTick(() => {
        if (!heatmapContainer.value) return
        
        if (chartInstance.value) {
          chartInstance.value.dispose()
        }
        
        chartInstance.value = echarts.init(heatmapContainer.value)
        
        const option = {
          tooltip: {
            position: 'top',
            formatter: (params) => {
              const months = ['7月', '8月', '9月', '10月', '11月']
              const depts = ['技术部', '市场部', '财务部', '人力资源部', '行政部']
              return `${months[params.value[0]]} ${depts[params.value[1]]}<br/>领用次数: ${params.value[2]}`
            }
          },
          grid: {
            height: '70%',
            top: '10%',
            left: '15%',
            right: '10%'
          },
          xAxis: {
            type: 'category',
            data: ['7月', '8月', '9月', '10月', '11月'],
            splitArea: {
              show: true
            }
          },
          yAxis: {
            type: 'category',
            data: ['技术部', '市场部', '财务部', '人力资源部', '行政部'],
            splitArea: {
              show: true
            }
          },
          visualMap: {
            min: 0,
            max: 50,
            calculable: true,
            orient: 'horizontal',
            left: 'center',
            bottom: '5%',
            inRange: {
              color: ['#e0f2ff', '#93c5fd', '#3b82f6', '#1d4ed8', '#1e3a8a']
            }
          },
          series: [{
            name: '领用次数',
            type: 'heatmap',
            data: heatData.value,
            label: {
              show: true,
              formatter: (params) => params.value[2]
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        }
        
        chartInstance.value.setOption(option)
        window.addEventListener('resize', handleResize)
      })
    }
    
    // 获取进度条颜色
    const getProgressColor = (index) => {
      const colors = ['#F56C6C', '#E6A23C', '#67C23A']
      return colors[index] || '#909399'
    }
    
    // 导出热力图
    const exportHeatMap = () => {
      if (chartInstance.value) {
        // 实际项目中可以导出为图片或其他格式
        const url = chartInstance.value.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff'
        })
        
        // 创建下载链接
        const link = document.createElement('a')
        link.download = `部门领用热度图_${new Date().toLocaleDateString()}.png`
        link.href = url
        link.click()
      } else {
        console.log('导出热力图')
        alert('热力图导出成功')
      }
    }
    
    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance.value) {
        chartInstance.value.resize()
      }
    }
    
    onMounted(() => {
      loadHeatData()
    })
    
    return {
      heatmapContainer,
      timeRange,
      assetType,
      rankingData,
      totalUsage,
      mostActiveDept,
      avgUsagePerDept,
      mostPopularCategory,
      getProgressColor,
      loadHeatData,
      exportHeatMap
    }
  }
}
</script>

<style scoped>
.dept-heat-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-controls .el-select {
  width: 150px;
}

.heatmap-card,
.ranking-card,
.summary-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.heatmap-container {
  width: 100%;
  height: 400px;
}

.ranking-list {
  padding: 10px 0;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.ranking-item:hover {
  background-color: #f5f7fa;
}

.ranking-item.top-three {
  background-color: #f0f9ff;
}

.ranking-number {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 50%;
  font-weight: bold;
  margin-right: 15px;
}

.ranking-item.top-three:nth-child(1) .ranking-number {
  background-color: #f56c6c;
  color: white;
}

.ranking-item.top-three:nth-child(2) .ranking-number {
  background-color: #e6a23c;
  color: white;
}

.ranking-item.top-three:nth-child(3) .ranking-number {
  background-color: #67c23a;
  color: white;
}

.ranking-info {
  flex: 1;
}

.dept-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.usage-count {
  font-size: 12px;
  color: #909399;
}

.ranking-value {
  width: 120px;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.summary-item {
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.summary-value {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.summary-label {
  font-size: 12px;
  color: #909399;
}
</style>